/*
 * @Author: weidewei
 * @Date: 2025-05-16 15:13:42
 * @LastEditors: weidewei
 * @LastEditTime: 2025-05-16 15:50:46
 * @Description: Axios 封装类（Class 版本）
 * @FilePath: \v2\src\http\index.js
 */

import axios from "axios";
import { encrypt,decrypt } from "utils/crypto";
import store from '@/store';
// import FakeProgress  from "fake-progress";
// const fake = new FakeProgress({

//   autoStart: true,
// })
class HttpClient {
  constructor(config = {}) {
    this.service = axios.create({
      baseURL: config.baseURL || "/api",
      timeout: config.timeout || 5000,
      headers: config.headers || {}
    });
    this.store = config.store;

    // 初始化拦截器
    this._initializeInterceptors();
  }

  // 初始化拦截器
  _initializeInterceptors() {
    let reqQueue = [];
    // 请求拦截器
    this.service.interceptors.request.use(
      (config) => {
        // 可在此处添加 token
        // const token = getToken();
        // if (token) config.headers.Authorization = `Bearer ${token}`;
        // console.log("requestConfig",encrypt(config.params))
        // const configCopy = {...config}
        // const copyParams = encrypt(configCopy.params)
        // const decryptParams = decrypt(copyParams)
        // console.log("requestConfig",copyParams)
        // console.log("requestConfig-de",decryptParams)
        // if(config.params) {
        //   config.params = encrypt(config.params)
        // }
        // if(config.data) {
        //   config.data = encrypt(config.data)
        // }
        // config = this._handleRequestProgress(config)
        if (this._needProgress(config)) {
          store.dispatch('progress/start', config)
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.service.interceptors.response.use(
      (response) => {
        const res = response.data;
        // 此处可添加业务状态码判断
        // if (res.code !== 200) {
        //   return Promise.reject(new Error(res.message || "Error"));
        // }
        // this._handleResponseProgress(response.config)
        if (this._needProgress(response.config)) {
          store.dispatch('progress/end', response.config)
        }
        return res;
      },
      (error) => {
        // this._handleResponseProgress(error.config)
        
        // 此处可添加全局错误处理
        if (this._needProgress(error.config)) {
          store.dispatch('progress/end', error.config)
        }
        return Promise.reject(error);
      }
    );
  }

  // 通用请求方法
  _request(method, url, data, options = {}) {
    const config = {
      method,
      url,
      ...options
    };

    if (method.toLowerCase() === "get") {
      config.params = data;
    } else {
      config.data = data;
    }

    return this.service(config);
  }

  _handleRequestProgress(config) {
    const progressConfig = {
      url: config.url,
      timer: null
    }
    this.store.dispatch('progress/startProgress', progressConfig)
    config.progressConfig = progressConfig
    return config
  }

  _handleResponseProgress(config) {
    if (config && config.progressConfig) {
      this.store.dispatch('progress/endProgress', config.progressConfig)
      if (config.progressConfig.timer) {
        clearInterval(config.progressConfig.timer)
      }
    }
  }

  // 判断是否需要显示进度
  _needProgress(config) {
    return !config.silent // 通过 config.silent 控制静默请求
  }

  // 封装的 GET 方法
  get(url, params, options) {
    return this._request("get", url, params, options);
  }

  // 封装的 POST 方法
  post(url, data, options) {
    return this._request("post", url, data, options);
  }

  // 其他 HTTP 方法
  put(url, data, options) {
    return this._request("put", url, data, options);
  }

  delete(url, params, options) {
    return this._request("delete", url, params, options);
  }
}

// 创建默认实例
const httpClient = new HttpClient({ store });

// 导出默认实例的直接调用方法
export const requestGet = (url, params, options) => httpClient.get(url, params, options);
export const requestPost = (url, data, options) => httpClient.post(url, data, options);
export const requestPut = (url, data, options) => httpClient.put(url, data, options);
export const requestDelete = (url, params, options) => httpClient.delete(url, params, options);

// 导出类用于特殊实例创建
export default httpClient;